import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/user_provider.dart';
import '../../utils/G.dart';

import 'package:image_picker/image_picker.dart';

class Profile extends StatefulWidget {
  Profile({Key? key}) : super(key: key);

  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  Map userInfo = {};
  final ImagePicker _picker = ImagePicker();
  File? _image;
  String _avatar = "";

  late TextEditingController _editingController;
  bool _isEditable = false;

  @override
  Widget build(BuildContext context) {
    userInfo = context.read<UserProvider>().userInfo;
    _editingController = TextEditingController(text: userInfo['nickname']);

    return Scaffold(
        appBar: AppBar(
          title: const Text('编辑用户'),
          centerTitle: true,
        ),
        body: ListView(
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          padding: const EdgeInsets.all(10),
          physics: const BouncingScrollPhysics(),
          children: [
            ListTile(
              title: const Text('用户头像'),
              trailing: InkWell(
                  child: _image == null
                      ? userInfo['avatar'] == ''
                          ? const Icon(Icons.supervised_user_circle_rounded,
                              size: 50)
                          : CircleAvatar(
                              backgroundImage:
                                  NetworkImage(userInfo['avatar'], scale: 1),
                            )
                      : CircleAvatar(
                          backgroundImage: FileImage(_image!, scale: 1),
                        ),
                  onTap: () {
                    // 点击更新用户头像
                    showModalBottomSheet(
                        context: context,
                        builder: (BuildContext context) {
                          return _renderBottomSheet(context);
                        });
                  }),
            ),
            ListTile(
              title: const Text('昵称'),
              trailing: _renderNickName(),
            ),
            ListTile(
              title: const Text('用户名'),
              trailing: Text(userInfo['real_name'].toString()),
            ),
            ListTile(
              title: const Text('手机号'),
              trailing: Text(userInfo['phone'].toString()),
            ),
            ListTile(
                title: const Text('密码'),
                trailing: InkWell(
                    child: const Text('修改密码'),
                    onTap: () {
                      // 跳转到修改密码页面
                      G.router.navigateTo(context, '/change_password');
                    })),
            Container(
                margin: const EdgeInsets.all(15),
                child: ElevatedButton(
                    onPressed: () async {
                      // 保存用户信息
                      _isEditable = false;
                      userInfo['nickname'] = _editingController.text;
                      if (_avatar != '') {
                        userInfo['avatar'] = _avatar;
                      }
                      var res = await G.api.user
                          .save(userInfo['avatar'], userInfo['nickname']);
                      if (res['status'] == 200) {
                        Provider.of<UserProvider>(context, listen: false)
                            .setUser(userInfo);
                        Future.delayed(const Duration(milliseconds: 500), () {
                          G.router.navigateTo(context, '/mine');
                        });
                      }
                    },
                    child: const Text('保存'),
                    style: ButtonStyle(
                        padding: MaterialStateProperty.all(
                            const EdgeInsets.all(12)))))
          ],
        ));
  }

  Widget _renderBottomSheet(BuildContext context) {
    return Container(
        height: 160,
        child: Column(
          children: [
            InkWell(
                onTap: () {
                  _takePhoto();
                  G.router.pop(context);
                },
                child: Container(
                    height: 50,
                    alignment: Alignment.center,
                    child: const Text('拍照'))),
            InkWell(
                onTap: () {
                  _openGallery();
                  G.router.pop(context);
                },
                child: Container(
                    height: 50,
                    alignment: Alignment.center,
                    child: const Text('从相册中选取'))),
            Container(
              color: Colors.grey.shade200,
              height: 10,
            ),
            InkWell(
                onTap: () {
                  G.router.pop(context);
                },
                child: Container(
                    height: 50,
                    alignment: Alignment.center,
                    child: const Text('取消'))),
          ],
        ));
  }

  // 拍照
  Future _takePhoto() async {
    final pickedFile = await _picker.pickImage(source: ImageSource.camera);

    if (pickedFile != null) {
      setState(() {
        _image = File(pickedFile.path);
        // 执行图片上传
        _uploadImage(pickedFile);
      });
    } else {
      G.error('未拍照');
    }
  }

  // 从相册中选取图片
  Future _openGallery() async {
    final pickedFile = await _picker.pickImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      setState(() {
        _image = File(pickedFile.path);
        // 执行图片上传
        _uploadImage(pickedFile);
      });
    } else {
      G.error('未选择图片');
    }
  }

  // 上传图片
  // pickedFile.path  /data/xxx/yyy/ccc/121212.jpg
  void _uploadImage(pickedFile) async {
    String filename = pickedFile.path.split('/').last.toString();
    var res = await G.api.user
        .uploadImage(imagePath: pickedFile.path, filename: filename);
    if (res['status'] == 200) {
      G.success('上传成功');
      // 将上传成功的图片路径，保存下载
      _avatar = res['data']['url'];
      print(_avatar);
    } else {
      G.error('上传失败');
    }
  }

  Widget _renderNickName() {
    if (_isEditable) {
      // 展示表单
      return Container(
          width: 60,
          child: TextField(
            controller: _editingController,
            textAlign: TextAlign.end,
            autofocus: true,
            onSubmitted: (value) {
              // print(value);
              // print(_editingController.text);
              setState(() {
                userInfo['nickname'] = _editingController.text;
                _isEditable = false;
              });
            },
          ));
    } else {
      // 展示文本
      return InkWell(
          onTap: () {
            setState(() {
              _isEditable = true;
            });
          },
          child: Text(userInfo['nickname'].toString()));
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _editingController.dispose();
  }
}
